#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

void backtrace(int QueueNum, vector<vector<string>> &res, vector<int> &stat_r,
               vector<int> &stat_c, vector<int> &stat_x, vector<int> &stat_t,
               vector<string> &t, int row) {
  if (row == QueueNum) {
    res.push_back(t);
    return;
  }
  string str(QueueNum, '.');
  for (int col = 0; col < QueueNum; col++) {
    if (stat_r[row] == 0 && stat_c[col] == 0 && stat_x[row + col] == 0 &&
        stat_t[col - row + (QueueNum - 1)] == 0) {
      stat_r[row] = 1;
      stat_c[col] = 1;
      stat_x[row + col] = 1;
      stat_t[col - row + (QueueNum - 1)] = 1;
      str[col] = 'Q';
      t.push_back(str);
      backtrace(QueueNum, res, stat_r, stat_c, stat_x, stat_t, t, row + 1);
      t.pop_back();
      str[col] = '.';
      stat_r[row] = 0;
      stat_c[col] = 0;
      stat_x[row + col] = 0;
      stat_t[col - row + (QueueNum - 1)] = 0;
    }
  }
}

vector<vector<string>> solveNQueens(int n) {
  // 行状态
  vector<int> stat_r(n, 0);
  // 列状态
  vector<int> stat_c(n, 0);
  // 斜对角线
  vector<int> stat_x(2 * n - 1, 0);
  // 反斜对角线
  vector<int> stat_t(2 * n - 1, 0);

  vector<vector<string>> res;
  vector<string> d;
  backtrace(n, res, stat_r, stat_c, stat_x, stat_t, d, 0);
  return res;
}